package org.gary.core.util;


import java.sql.*;
import java.util.*;

import org.springframework.stereotype.Component;
/**
 * dao层工具类
 * @author Gary
 *
 */
@Component("dbUtil")
public class DBUtile {
	private Connection conn;
	private PreparedStatement ps;
	ResultSet rs;

	/**
	 * 构造方法
	 */
	public DBUtile() {
		// getConnection();
	}

	/**
	 * 得到数据库连接
	 */
	private void getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/rmrltd?useUnicode=true&characterEncoding=utf-8","root","123456"); 
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 增删改语句的执行方法 list可以传null进去
	 * 
	 * @param sql
	 *            数据库操作语句
	 * @param list
	 *            参数列表
	 * @return 返回int类型值，影响了几条记录
	 */
	@SuppressWarnings("unchecked")
	public int execuetUpdate(String sql, List list) throws Exception {
		getConnection();
		int n = 0;
		System.out.println(sql);
		ps = conn.prepareStatement(sql);
		for (int i = 0; list != null && i < list.size(); i++) {
			ps.setObject(i + 1, list.get(i));
		}
		n = ps.executeUpdate();
		System.out.println(sql);
		return n;
	}

	/**
	 * 查询语句的执行方法 list可以传null进去
	 * 
	 * @param sql
	 *            数据库操作语句
	 * @param list
	 *            参数列表
	 * @return 返回一个结果集
	 */
	@SuppressWarnings("unchecked")
	public ResultSet execuetQuery(String sql, List list) throws Exception {
		getConnection();
		ps = conn.prepareStatement(sql);
		for (int i = 0; list != null && i < list.size(); i++) {
			ps.setObject(i + 1, list.get(i));
		}
		rs = ps.executeQuery();

		return rs;

	}

	public void closedAll() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
